using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Threading.Tasks;
using DesktopWidgetApp.Shared;

namespace DesktopWidgetApp.Client.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Point _startPoint;
        // 简化版：使用基本字段替代不存在的服务
        private int _currentUserId = 1; // 保留字段，用于将来实现完整功能（当前模拟用户ID）
        private Status _currentStatus = new Status { Type = StatusType.Working, IsDoNotDisturb = false };
        
        public MainWindow()
        {
            InitializeComponent();

            // 简化初始化，仅支持基本功能
            InitializeUI();

            // 设置窗口关闭事件
            this.Closing += MainWindow_Closing;

            // 应用当前样式
            ApplyCurrentStyle();
        }

        /// <summary>
        /// 任务管理按钮点击事件
        /// </summary>
        private void TaskManagerButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开任务管理窗口
                var taskManagerWindow = new TaskManagerWindow();
                taskManagerWindow.Owner = this;
                taskManagerWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("操作失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 窗口关闭事件处理
        /// </summary>
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 取消关闭，改为隐藏窗口
            e.Cancel = true;
            this.Hide();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            
            // 简化的资源清理
        }

        /// <summary>
        /// 初始化用户界面
        /// </summary>
        private void InitializeUI()
        {
            try
            {
                // 简化的初始化，不依赖_statusService
                // 默认设置为工作中状态
                CurrentStatusText.Text = "工作中";
                StatusIndicator.Fill = Brushes.Green;
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化状态显示失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 设置状态同步定时器（当前未使用）
        /// </summary>
        private void SetupSyncTimer()
        {
            // 当前版本不实现同步功能
        }

        private void ApplyCurrentStyle()
        {
            // 简化版：不实现样式管理
            // 保留默认WPF样式
        }

        private void OnStyleChanged(object sender, EventArgs e)
        {
            // 简化版：不实现样式管理
        }

        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 简化版：显示提示信息
            MessageBox.Show("设置功能在当前版本中不可用", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 同步状态数据（当前版本不实现网络同步）
        /// </summary>
        private void SyncStatusAsync()
        {
            try
            {
                // 简化版：只更新本地UI，不进行网络同步
                UpdateStatusDisplay(_currentStatus);
            }
            catch (Exception ex)
            {
                // 同步失败不显示错误，避免打扰用户
                Console.WriteLine("状态更新失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatusDisplay(Status status)
        {
            // 更新状态文本
            CurrentStatusText.Text = GetStatusDisplayName(status.Type);
            
            // 更新状态指示器颜色
            StatusIndicator.Fill = GetStatusColor(status.Type);
            
            // 更新免打扰开关
            DoNotDisturbToggle.IsChecked = status.IsDoNotDisturb;
            DoNotDisturbText.Text = status.IsDoNotDisturb ? "开" : "关";
        }

        /// <summary>
        /// 获取状态显示名称
        /// </summary>
        private string GetStatusDisplayName(StatusType statusType)
        {
            switch (statusType)
            {
                case StatusType.Working: return "工作中";
                case StatusType.InMeeting: return "会议中";
                case StatusType.OnBreak: return "休息中";
                case StatusType.OutOfOffice: return "外出";
                case StatusType.Custom: return "自定义";
                default: return "未知";
            }
        }

        /// <summary>
        /// 获取状态对应的颜色
        /// </summary>
        private Brush GetStatusColor(StatusType statusType)
        {
            switch (statusType)
            {
                case StatusType.Working: return Brushes.Green;
                case StatusType.InMeeting: return Brushes.Orange;
                case StatusType.OnBreak: return Brushes.Blue;
                case StatusType.OutOfOffice: return Brushes.Red;
                case StatusType.Custom: return Brushes.Purple;
                default: return Brushes.Gray;
            }
        }

        /// <summary>
        /// 标题栏鼠标按下事件 - 实现窗口拖动
        /// </summary>
        private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _startPoint = e.GetPosition(null);
                this.DragMove();
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Hide(); // 隐藏窗口而不是关闭应用程序
        }

        /// <summary>
        /// 状态按钮点击事件
        /// </summary>
        private void StatusButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var button = sender as FrameworkElement;
                if (button != null && Enum.TryParse<StatusType>(button.Tag.ToString(), out var statusType))
                {
                    var isDoNotDisturb = DoNotDisturbToggle.IsChecked ?? false;
                    
                    // 简化版：更新本地状态
                    _currentStatus.Type = statusType;
                    _currentStatus.IsDoNotDisturb = isDoNotDisturb;
                    
                    // 更新UI显示
                    UpdateStatusDisplay(_currentStatus);
                    
                    // 显示状态更新成功信息
                    MessageBox.Show("状态已更新: " + GetStatusDisplayName(statusType), "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新状态失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 免打扰开关选中事件
        /// </summary>
        private void DoNotDisturbToggle_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DoNotDisturbText.Text = "开";
                UpdateDoNotDisturbStatus(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置免打扰失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 免打扰开关取消选中事件
        /// </summary>
        private void DoNotDisturbToggle_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                DoNotDisturbText.Text = "关";
                UpdateDoNotDisturbStatus(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show("取消免打扰失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新免打扰状态
        /// </summary>
        private void UpdateDoNotDisturbStatus(bool isDoNotDisturb)
        {
            // 简化版：直接更新本地状态
            _currentStatus.IsDoNotDisturb = isDoNotDisturb;
            
            // 显示操作成功信息
            MessageBox.Show(
                isDoNotDisturb ? "免打扰模式已开启" : "免打扰模式已关闭", 
                "成功", 
                MessageBoxButton.OK, 
                MessageBoxImage.Information
            );
        }
    }
}